document.addEventListener('DOMContentLoaded', function() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');
    const pendingOrdersContainer = document.getElementById('pendingOrders');
    const deliveringOrdersContainer = document.getElementById('deliveringOrders');
    const historyOrdersContainer = document.getElementById('historyOrders');
    const orderDetailModal = document.getElementById('orderDetailModal');
    const closeDetail = document.getElementsByClassName('close')[0];
    const orderDetailContent = document.getElementById('orderDetailContent');
    const logoutBtn = document.getElementById('logoutBtn');
    
    // 模拟订单数据
    let pendingOrders = [
        { id: 1, userId: 101, username: '张三', orderTime: '2023-10-15 20:30', totalAmount: 56, address: '学生公寓1号楼302室', status: '待配送',
          items: [{ foodId: 1, foodName: '红烧肉', quantity: 1, price: 25 }, { foodId: 5, foodName: '麻婆豆腐', quantity: 1, price: 16 }, { foodId: 3, foodName: '鱼香肉丝', quantity: 1, price: 15 }] },
        { id: 2, userId: 102, username: '李四', orderTime: '2023-10-15 20:45', totalAmount: 48, address: '学生公寓2号楼501室', status: '待配送',
          items: [{ foodId: 2, foodName: '宫保鸡丁', quantity: 1, price: 22 }, { foodId: 6, foodName: '回锅肉', quantity: 1, price: 26 }] }
    ];
    
    let deliveringOrders = [
        { id: 3, userId: 103, username: '王五', orderTime: '2023-10-15 20:00', totalAmount: 72, address: '学生公寓3号楼205室', status: '配送中',
          items: [{ foodId: 1, foodName: '红烧肉', quantity: 2, price: 25 }, { foodId: 4, foodName: '糖醋排骨', quantity: 1, price: 28 }] }
    ];
    
    let historyOrders = [
        { id: 4, userId: 104, username: '赵六', orderTime: '2023-10-15 19:30', totalAmount: 36, address: '学生公寓1号楼403室', status: '已完成',
          items: [{ foodId: 3, foodName: '鱼香肉丝', quantity: 1, price: 15 }, { foodId: 5, foodName: '麻婆豆腐', quantity: 1, price: 16 }] },
        { id: 5, userId: 105, username: '钱七', orderTime: '2023-10-15 19:45', totalAmount: 44, address: '学生公寓2号楼102室', status: '已完成',
          items: [{ foodId: 2, foodName: '宫保鸡丁', quantity: 2, price: 22 }] }
    ];
    
    // 切换标签页
    function openTab(evt, tabName) {
        // 隐藏所有内容
        tabContents.forEach(content => {
            content.classList.remove('active');
        });
        
        // 移除所有按钮的激活状态
        tabBtns.forEach(btn => {
            btn.classList.remove('active');
        });
        
        // 显示当前标签页内容
        document.getElementById(tabName).classList.add('active');
        
        // 设置当前按钮为激活状态
        evt.currentTarget.classList.add('active');
        
        // 根据标签页显示相应的订单
        if (tabName === 'pendingOrders') {
            displayOrders(pendingOrders, pendingOrdersContainer, true);
        } else if (tabName === 'deliveringOrders') {
            displayOrders(deliveringOrders, deliveringOrdersContainer, false, true);
        } else if (tabName === 'historyOrders') {
            displayOrders(historyOrders, historyOrdersContainer, false);
        }
    }
    
    // 显示订单列表
    function displayOrders(orders, container, showAcceptBtn = false, showCompleteBtn = false) {
        container.innerHTML = '';
        
        if (orders.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #666;">暂无订单</p>';
            return;
        }
        
        orders.forEach(order => {
            const orderItem = document.createElement('div');
            orderItem.className = 'order-item';
            
            let statusClass = '';
            switch(order.status) {
                case '待配送':
                    statusClass = 'status-pending';
                    break;
                case '配送中':
                    statusClass = 'status-delivering';
                    break;
                case '已完成':
                    statusClass = 'status-completed';
                    break;
            }
            
            orderItem.innerHTML = `
                <div class="order-header">
                    <div>订单号: #${order.id}</div>
                    <div class="order-status ${statusClass}">${order.status}</div>
                </div>
                <div class="order-info">
                    <p>用户: ${order.username}</p>
                    <p>下单时间: ${order.orderTime}</p>
                    <p>地址: ${order.address}</p>
                    <p>总金额: ¥${order.totalAmount.toFixed(2)}</p>
                </div>
                <div class="order-actions">
                    <button class="btn-view-detail" data-id="${order.id}" data-status="${order.status}">查看详情</button>
                    ${showAcceptBtn ? `<button class="btn-accept" data-id="${order.id}">接单</button>` : ''}
                    ${showCompleteBtn ? `<button class="btn-complete" data-id="${order.id}">完成配送</button>` : ''}
                </div>
            `;
            
            container.appendChild(orderItem);
        });
        
        // 添加事件监听
        document.querySelectorAll('.btn-view-detail').forEach(button => {
            button.addEventListener('click', viewOrderDetail);
        });
        
        document.querySelectorAll('.btn-accept').forEach(button => {
            button.addEventListener('click', acceptOrder);
        });
        
        document.querySelectorAll('.btn-complete').forEach(button => {
            button.addEventListener('click', completeOrder);
        });
    }
    
    // 查看订单详情
    function viewOrderDetail(event) {
        const orderId = parseInt(event.target.getAttribute('data-id'));
        const orderStatus = event.target.getAttribute('data-status');
        
        // 查找订单
        let order = null;
        if (orderStatus === '待配送') {
            order = pendingOrders.find(o => o.id === orderId);
        } else if (orderStatus === '配送中') {
            order = deliveringOrders.find(o => o.id === orderId);
        } else if (orderStatus === '已完成') {
            order = historyOrders.find(o => o.id === orderId);
        }
        
        if (order) {
            // 显示订单详情
            let itemsHtml = '';
            order.items.forEach(item => {
                itemsHtml += `
                    <tr>
                        <td>${item.foodName}</td>
                        <td>${item.quantity}</td>
                        <td>¥${item.price.toFixed(2)}</td>
                        <td>¥${(item.price * item.quantity).toFixed(2)}</td>
                    </tr>
                `;
            });
            
            orderDetailContent.innerHTML = `
                <h2>订单详情</h2>
                <div class="order-info">
                    <p><strong>订单号:</strong> #${order.id}</p>
                    <p><strong>用户:</strong> ${order.username}</p>
                    <p><strong>下单时间:</strong> ${order.orderTime}</p>
                    <p><strong>地址:</strong> ${order.address}</p>
                    <p><strong>状态:</strong> ${order.status}</p>
                </div>
                <table class="order-items-table">
                    <tr>
                        <th>菜品名称</th>
                        <th>数量</th>
                        <th>单价</th>
                        <th>小计</th>
                    </tr>
                    ${itemsHtml}
                </table>
                <div class="order-total">
                    <h3>总金额: ¥${order.totalAmount.toFixed(2)}</h3>
                </div>
            `;
            
            orderDetailModal.style.display = 'block';
        }
    }
    
    // 接单
    function acceptOrder(event) {
        const orderId = parseInt(event.target.getAttribute('data-id'));
        const orderIndex = pendingOrders.findIndex(o => o.id === orderId);
        
        if (orderIndex !== -1) {
            const order = pendingOrders[orderIndex];
            order.status = '配送中';
            
            // 从待配送列表移除，添加到配送中列表
            pendingOrders.splice(orderIndex, 1);
            deliveringOrders.push(order);
            
            // 更新UI
            displayOrders(pendingOrders, pendingOrdersContainer, true);
            displayOrders(deliveringOrders, deliveringOrdersContainer, false, true);
            
            alert('接单成功');
        }
    }
    
    // 完成配送
    function completeOrder(event) {
        const orderId = parseInt(event.target.getAttribute('data-id'));
        const orderIndex = deliveringOrders.findIndex(o => o.id === orderId);
        
        if (orderIndex !== -1) {
            const order = deliveringOrders[orderIndex];
            order.status = '已完成';
            
            // 从配送中列表移除，添加到历史订单列表
            deliveringOrders.splice(orderIndex, 1);
            historyOrders.push(order);
            
            // 更新UI
            displayOrders(deliveringOrders, deliveringOrdersContainer, false, true);
            displayOrders(historyOrders, historyOrdersContainer, false);
            
            alert('配送完成');
        }
    }
    
    // 事件监听
    tabBtns.forEach(btn => {
        btn.addEventListener('click', function(evt) {
            openTab(evt, this.textContent === '待配送' ? 'pendingOrders' : 
                      this.textContent === '配送中' ? 'deliveringOrders' : 'historyOrders');
        });
    });
    
    closeDetail.addEventListener('click', function() {
        orderDetailModal.style.display = 'none';
    });
    
    window.addEventListener('click', function(event) {
        if (event.target === orderDetailModal) {
            orderDetailModal.style.display = 'none';
        }
    });
    
    logoutBtn.addEventListener('click', function() {
        // 清除用户信息
        localStorage.removeItem('user');
        
        // 跳转到登录页面
        window.location.href = 'login.html';
    });
    
    // 初始化页面，显示待配送订单
    tabBtns[0].click();
    
    // 获取用户信息
    const user = JSON.parse(localStorage.getItem('user'));
    if (user) {
        document.getElementById('usernameDisplay').textContent = user.username;
    }
});